package com.example.langchain4j.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class DocumentUtils {

    public static  String extractTextFromWord(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new IllegalArgumentException("File name cannot be null");
        }

        String fileExtension = getFileExtension(fileName);

        try (InputStream inputStream = file.getInputStream()) {
            switch (fileExtension.toLowerCase()) {
                case "docx":
                    return extractFromDocx(inputStream);
                case "doc":
                    return extractFromDoc(inputStream);
                default:
                    throw new IllegalArgumentException("Unsupported file format: " + fileExtension);
            }
        }
    }

    private static  String extractFromDocx(InputStream inputStream) throws IOException {
        StringBuilder content = new StringBuilder();

        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            // Extract paragraphs
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                String text = paragraph.getText();
                if (text != null && !text.trim().isEmpty()) {
                    content.append(text).append("\n");
                }
            }

            // Extract tables
            List<XWPFTable> tables = document.getTables();
            for (XWPFTable table : tables) {
                content.append("\n[Table]\n");
                for (XWPFTableRow row : table.getRows()) {
                    StringBuilder rowText = new StringBuilder();
                    for (XWPFTableCell cell : row.getTableCells()) {
                        String cellText = cell.getText();
                        if (cellText != null && !cellText.trim().isEmpty()) {
                            rowText.append(cellText).append("\t");
                        }
                    }
                    if (rowText.length() > 0) {
                        content.append(rowText.toString().trim()).append("\n");
                    }
                }
                content.append("[/Table]\n\n");
            }
        }

        return content.toString().trim();
    }

    private static  String extractFromDoc(InputStream inputStream) throws IOException {
        try (HWPFDocument document = new HWPFDocument(inputStream);
             WordExtractor extractor = new WordExtractor(document)) {
            return extractor.getText();
        }
    }

    private static  String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex == -1) {
            return "";
        }
        return fileName.substring(dotIndex + 1);
    }

    public boolean isWordDocument(String fileName) {
        if (fileName == null) {
            return false;
        }
        String extension = getFileExtension(fileName).toLowerCase();
        return "doc".equals(extension) || "docx".equals(extension);
    }
}